import datetime
from django.utils import timezone
from django.core.cache import cache
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import render, redirect
from django.db.models import Sum
from django.core.paginator import Paginator
from django.conf import settings
from django.db.models import Q

from blog.models import Blog
from read_record.utils import last_seven_days_read_detail, get_one_day_hot_detail

def get_past_hot_detail(days):
    '''
    获取过去days中的热门博客
    '''
    today = timezone.now().date()
    date_lower_bound = today - datetime.timedelta(days=days)
    blogs = Blog.objects.filter(read_detail__date__lt=today, read_detail__date__gte=date_lower_bound)\
                        .values('pk', 'title')\
                        .annotate(read_num_sum=Sum('read_detail__read_num'))\
                        .order_by('-read_num_sum')
    return blogs[:7]

def home(request):
    blog_ct = ContentType.objects.get_for_model(Blog)
    # 获取历史7天阅读量
    dates, read_sums = last_seven_days_read_detail(blog_ct)
    # 获取今天热门博客
    today = timezone.now().date()
    today_hot_read_detail = get_one_day_hot_detail(today)
    # 获取昨天热门博客
    yesterday = today - datetime.timedelta(days=1)
    yesterday_hot_read_detail = get_one_day_hot_detail(yesterday)
    # 获取历史7天热门博客(使用数据库缓存，缓存有效时间为1h)
    past_7_hot_detail = cache.get('past_7_hot_detail')
    if past_7_hot_detail is None:
        past_7_hot_detail = get_past_hot_detail(7)
        cache.set('past_7_hot_detail', past_7_hot_detail, 3600)
    context = {}
    context['dates'] = dates
    context['read_sums'] = read_sums
    context['today_hot_details'] = today_hot_read_detail
    context['yesterday_hot_details'] = yesterday_hot_read_detail
    context['past_7_hot_detail'] = past_7_hot_detail
    return render(request, 'home.html', context)

def search(request):
    '''
    用GET方法接受关键字wd
    '''
    search_word = request.GET.get('wd').strip()
    # 分词
    search_words = search_word.split(' ')
    # 搜索逻辑或
    condition = None
    for word in search_words:
        if condition is None:
            condition = Q(title__icontains=word)
        else:
            condition |= Q(title__icontains=word)
    context = {}
    context['search_word'] = search_word
    if condition is not None:
        searched_blogs = Blog.objects.filter(condition)
        paginator = Paginator(searched_blogs, settings.BLOGS_PER_PAGE)
        page_num = request.GET.get('page', 1)
        page_of_blogs = paginator.get_page(page_num)
        page_num = page_of_blogs.number
        page_range = list(range(max(1, page_num - 2), min(page_num + 3, paginator.num_pages + 1)))
        # 加上页面的省略标记
        if page_range[0] - 1 > 1:
            page_range.insert(0, '...')
        if paginator.num_pages - page_range[-1] > 1:
            page_range.append('...')
        # 加上首页和尾页
        if page_range[0] != 1:
            page_range.insert(0, 1)
        if page_range[-1] != paginator.num_pages:
            page_range.append(paginator.num_pages)
    else:
        # 没有输入搜索信息
        page_of_blogs = []
        page_range = []
    context['page_of_blogs'] = page_of_blogs
    context['page_range'] = page_range
    return render(request, 'search.html', context)